import json
import subprocess
import time
import psutil

def load_programs_config(config_file):
    """Load programs to monitor from a JSON config file."""
    with open(config_file, "r") as file:
        return json.load(file)

def is_program_running(program_name):
    """Check if a program is running."""
    for proc in psutil.process_iter(attrs=["pid", "name", "cmdline"]):
        try:
            cmdline = " ".join(proc.info["cmdline"])
            if program_name in cmdline:
                return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False

def restart_program(command):
    """Restart the program using the given command."""
    print(f"Restarting program: {command}")
    subprocess.Popen(command, shell=True)

def monitor_programs(programs, check_interval=5):
    """Monitor and restart programs if they are not running."""
    while True:
        for program in programs:
            name = program["name"]
            command = program["command"]

            if not is_program_running(name):
                print(f"{name} is not running. Restarting...")
                restart_program(command)

        time.sleep(check_interval)

if __name__ == "__main__":
    config_file = "programs.json"
    programs = load_programs_config(config_file)

    print("Starting program monitor...")
    monitor_programs(programs)